package com.jht.bletool2java.activity.blepage.fragment.log;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jht.bletool2java.BLEApplication;
import com.jht.bletool2java.R;
import com.jht.bletool2java.activity.blepage.fragment.log.adapter.BlePrintLogAdapter;
import com.jht.bletool2java.activity.blepage.fragment.log.bean.DataLog;
import com.jht.bletool2java.activity.homepage.fragment.bledevice.bean.BLEDevice;
import com.jht.bletool2java.util.ByteUtil;
import com.jht.bletool2java.util.DateUtil;
import com.suke.widget.SwitchButton;



import static com.jht.bletool2java.service.BLEService.ACTION_GATT_CONNECTED;
import static com.jht.bletool2java.service.BLEService.ACTION_GATT_DISCONNECTED;
import static com.jht.bletool2java.service.BLEService.ACTION_GATT_SERVICES_DISCOVERED;
import static com.jht.bletool2java.service.BLEService.ACTION_MTU_CHANGE;
import static com.jht.bletool2java.service.BLEService.ACTION_NOTIFY_DATA;
import static com.jht.bletool2java.service.BLEService.ACTION_READ_DATA_OK;
import static com.jht.bletool2java.service.BLEService.ACTION_WRITE_DATA_OK;
import static com.jht.bletool2java.service.BLEService.EXTRA_DATA_CURRENT_CHARACTERISTIC_DATA;
import static com.jht.bletool2java.service.BLEService.EXTRA_DATA_CURRENT_CHARACTERISTIC_NAME;


public class BleLogFragment extends Fragment {
    private static final String TAG = "BleLogFragment";
    private BLEDevice bluetoothDevice;
    private LinearLayout mIvEmptyView;
    private RecyclerView mRvPrintLog;
    private BlePrintLogAdapter blePrintLogAdapter;
    private LinearLayout mLlRvParent;
    private SwitchButton mSwitchButton;
    private long currentTime = 0;
    private boolean isRecordTime = false; //是否记录过时间
    private boolean pause = false; //是否fragment暂停
    private BLELogReceiver dataLogReceiver = new BLELogReceiver();

    public BleLogFragment(BLEDevice ble_device) {
        bluetoothDevice = ble_device;
    }

    public static BleLogFragment newInstance(BLEDevice ble_device) {
        return new BleLogFragment(ble_device);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_GATT_CONNECTED);
        intentFilter.addAction(ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(ACTION_MTU_CHANGE);
        intentFilter.addAction(ACTION_READ_DATA_OK);
        intentFilter.addAction(ACTION_NOTIFY_DATA);
        intentFilter.addAction(ACTION_WRITE_DATA_OK);
        BLEApplication.getBLEApplicationContext().registerReceiver(dataLogReceiver,intentFilter);

        Log.i(TAG, "onCreate: registerReceiver");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_ble_data_log, container, false);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRvPrintLog = view.findViewById(R.id.rv_print_log);
        mSwitchButton = view.findViewById(R.id.switch_button);
        mRvPrintLog.setOnTouchListener(new View.OnTouchListener() {
            float lastY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        lastY = event.getY();
                        break;
                    case MotionEvent.ACTION_UP:
                        if (event.getY() - lastY > 0) {
                            mSwitchButton.setChecked(false);
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });

        mIvEmptyView = view.findViewById(R.id.iv_empty_view);
        mLlRvParent = view.findViewById(R.id.ll_rv_parent);

        mSwitchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            /**
             *
             * @param view 表示SwitchButton
             * @param isChecked 代表当前按钮的 check 状态
             */
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (!isChecked) {
                    isRecordTime = true;
                    currentTime = System.currentTimeMillis();
                }
            }
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false);
        mRvPrintLog.setLayoutManager(linearLayoutManager);
        blePrintLogAdapter = new BlePrintLogAdapter(getActivity());
        mRvPrintLog.setAdapter(blePrintLogAdapter);

    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e(TAG, "onPause: 日志暂停");
        if (mSwitchButton.isChecked()) {
            isRecordTime = true;
            currentTime = System.currentTimeMillis();
        }
        pause = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG, "onResume: 日志继续");
        pause = false;
    }

    private void updateLog(DataLog dataLog) {
        mIvEmptyView.setVisibility(View.GONE);
        mRvPrintLog.setVisibility(View.VISIBLE);
        mLlRvParent.setVisibility(View.VISIBLE);
        Log.d(TAG, "updateLog: ================");
        blePrintLogAdapter.addData(dataLog);
        // 自动滚动 需要被控制
        if (mSwitchButton.isChecked()) {
            if (pause) {
                return;
            }
            if (isRecordTime) { //表示之前记录过时间，则可以不采用平滑滚动
                long temp = System.currentTimeMillis();
                if (temp - currentTime > 15 * 1000) {
                    mRvPrintLog.scrollToPosition(blePrintLogAdapter.getItemCount() - 1);
                } else {
                    mRvPrintLog.smoothScrollToPosition(blePrintLogAdapter.getItemCount() - 1);
                }
                isRecordTime = false;
            } else {
                mRvPrintLog.smoothScrollToPosition(blePrintLogAdapter.getItemCount() - 1);
            }

        }
    }

    public void clearAllLog() {
        blePrintLogAdapter.clear();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BLEApplication.getBLEApplicationContext().unregisterReceiver(dataLogReceiver);
    }

    public void showToast(int msgId) {
        String msg = getResources().getString(msgId);
        Toast.makeText(BLEApplication.getBLEApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }

    private class BLELogReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) return;
            String uuid = intent.getStringExtra(EXTRA_DATA_CURRENT_CHARACTERISTIC_NAME);

            byte[] ble_data = intent.getByteArrayExtra(EXTRA_DATA_CURRENT_CHARACTERISTIC_DATA);
            DataLog dataLog = null;
            switch (action){
                case ACTION_GATT_CONNECTED:
                    dataLog = new DataLog(DateUtil.getCurrentTime(), "", "device has connected", Color.parseColor("#1E90FF"));
                    updateLog(dataLog);
                    break;
                case ACTION_GATT_DISCONNECTED:
                    break;
                case ACTION_GATT_SERVICES_DISCOVERED:
                    break;
                case ACTION_READ_DATA_OK:
                    if (ble_data != null && uuid != null){
                        String sub_uuid = uuid.substring(0, 9);
                        dataLog = new DataLog(DateUtil.getCurrentTime(), "[" + sub_uuid + "]:read: ", "" + ByteUtil.getHexString(ble_data), Color.parseColor("#1E90FF"));
                    }else {
                        dataLog = new DataLog(DateUtil.getCurrentTime(), "", "read characteristic fail!!", Color.parseColor("#ff0000"));
                    }
                    updateLog(dataLog);
                    break;
                case ACTION_WRITE_DATA_OK:
                    break;
                case ACTION_NOTIFY_DATA:
                    if (ble_data != null && uuid != null){
                        String sub_uuid = uuid.substring(0, 9);
                        dataLog = new DataLog(DateUtil.getCurrentTime(), "[" + sub_uuid + "]:notify: ", "" + ByteUtil.getHexString(ble_data), Color.parseColor("#00A2E8"));
                    }else {
                        dataLog = new DataLog(DateUtil.getCurrentTime(), "", "notify characteristic fail!!", Color.parseColor("#ff0000"));
                    }
                    updateLog(dataLog);
                    break;
                case ACTION_MTU_CHANGE:
                    break;
            }

        }
    }

}